import { defineStore } from 'pinia';
import { ref, computed, watch, readonly } from 'vue'; // Import readonly
import { v4 as uuidv4 } from 'uuid';
import * as idbService from '@/utils/indexedDBService'; // Import IndexedDB service
import { ElMessage, ElMessageBox, type UploadRawFile } from 'element-plus'; // Import Element Plus components
import { useSettingsStore } from './settingsStore'; // Import settings store if needed (e.g., for confirmation)
import { useEditorStore } from './editorStore'; // Import editor store

// Type definitions
type StoredJDFFileMeta = idbService.StoredJDFFileMeta;
type StoredJDFFolderMeta = idbService.StoredJDFFolderMeta;
type FilesystemItemMeta = idbService.FilesystemItemMeta;
type StoredJDFFolder = idbService.StoredJDFFolder;
// Add StoredJDFFile type if not already defined globally
type StoredJDFFile = idbService.StoredJDFFile;

// Constants
const ROOT_FOLDER_ID = null; // Consistent reference to root

// --- Define Sort Types ---
export type SortKey = 'name' | 'type' | 'size' | 'lastModified';
export type SortDirection = 'asc' | 'desc';
// -------------------------

// Helper function for confirmation
async function confirm(message: string): Promise<boolean> {
    try {
        await ElMessageBox.confirm(message, '确认操作', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });
        return true;
    } catch (action) {
        // action will be 'cancel' or 'close' if the user dismisses the dialog
        if (action === 'cancel') {
            ElMessage.info('操作已取消');
        }
        return false;
    }
}

// --- Refactor to Setup Store --- 
export const useFileManagerStore = defineStore('fileManager', () => {
    console.log('[fileManagerStore] Initializing store...');
    // --- State (as refs) ---
    const _currentItems = ref<FilesystemItemMeta[]>([]); // Renamed internal state
    const currentFolderId = ref<string | null>(ROOT_FOLDER_ID);
    const breadcrumbs = ref<{ name: string, uuid: string | null }[]>([{ name: '根目录', uuid: ROOT_FOLDER_ID }]);
    const isDBLoading = ref<boolean>(false);
    const error = ref<string | null>(null);

    // --- New Sorting State ---
    const sortKey = ref<SortKey>('name');
    const sortDirection = ref<SortDirection>('asc');
    // --------------------------

    // --- Getters (as computeds) ---
    const currentFolderName = computed((): string => {
        // console.log('[fileManagerStore computed] currentFolderName evaluated.');
        return breadcrumbs.value[breadcrumbs.value.length - 1]?.name ?? '根目录';
    });

    // --- Computed Property for Sorted Items ---
    const currentItems = computed(() => {
        console.log(`[fileManagerStore computed currentItems] Sorting based on: ${sortKey.value} ${sortDirection.value}`);
        // Read from the renamed internal state _currentItems
        const itemsToSort = [..._currentItems.value];

        // Helper function to get a consistent type string for sorting
        const getTypeString = (item: FilesystemItemMeta): string => {
            if (item.type === 'folder') return ' folder';
            const extension = item.name.split('.').pop()?.toLowerCase() || 'file';
            return extension;
        }

        // Apply sorting based on state
        itemsToSort.sort((a, b) => {
            const direction = sortDirection.value === 'asc' ? 1 : -1;
            const key = sortKey.value;
            let comparison = 0;

            // 1. Handle folder vs file first (folders first always)
            if (a.type !== b.type) {
                comparison = (a.type === 'folder' ? -1 : 1);
                return comparison;
            }

            // 2. Compare based on the sort key
            let valA: any;
            let valB: any;

            if (key === 'type') {
                valA = getTypeString(a);
                valB = getTypeString(b);
                comparison = valA.localeCompare(valB);
            } else if (key === 'name') {
                valA = a.name;
                valB = b.name;
                comparison = valA.localeCompare(valB, undefined, { numeric: true, sensitivity: 'base' });
            } else if (key === 'size') {
                valA = a.size ?? 0;
                valB = b.size ?? 0;
                comparison = valA - valB;
            } else if (key === 'lastModified') {
                valA = a.lastModified ? new Date(a.lastModified).getTime() : 0;
                valB = b.lastModified ? new Date(b.lastModified).getTime() : 0;
                if (isNaN(valA)) valA = 0;
                if (isNaN(valB)) valB = 0;
                comparison = valA - valB;
            }

            // 3. Apply direction
            comparison *= direction;

            // 4. Secondary Sort by name
            if (comparison === 0 && key !== 'name') {
                comparison = a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
            }

            return comparison;
        });

        console.log('[fileManagerStore computed currentItems] Sorting complete.');
        return itemsToSort;
    });

    // --- Actions (as functions) ---
    const loadFolderItems = async (folderId?: string | null) => {
        const targetFolderId = folderId === undefined ? currentFolderId.value : folderId;
        console.log(`[fileManagerStore loadFolderItems] START - Loading items for target folder: ${targetFolderId}`); 
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore loadFolderItems] Aborted: Already loading.`);
            return;
        }
        isDBLoading.value = true;
        error.value = null;
        try {
            console.log(`[fileManagerStore loadFolderItems] Calling idbService.getItemsByParent for: ${targetFolderId}`); 
            const items = await idbService.getItemsByParent(targetFolderId);
            console.log(`[fileManagerStore loadFolderItems] Received ${items.length} items from DB for: ${targetFolderId}`);
            // Modify state AFTER successful DB call
            console.log(`[fileManagerStore loadFolderItems] Updating state: currentItems, currentFolderId`);
            _currentItems.value = items;

            // --- FIX: Always update currentFolderId to the ID of the folder whose items were just loaded --- 
            console.log(`[fileManagerStore loadFolderItems] >>> Updating currentFolderId from ${currentFolderId.value} to ${targetFolderId}`);
            currentFolderId.value = targetFolderId;
            console.log(`[fileManagerStore loadFolderItems] >>> currentFolderId is NOW ${currentFolderId.value}`);
            
            console.log(`[fileManagerStore loadFolderItems] State updated. Final currentFolderId: ${currentFolderId.value}, items count: ${_currentItems.value.length}`); 
        } catch (err: any) {
            error.value = `加载文件夹内容失败 (ID: ${targetFolderId}): ${err.message}`;
            // Optionally clear items on error, or leave them stale?
            // _currentItems.value = []; 
            console.error('[fileManagerStore loadFolderItems] Error loading items:', err);
            ElMessage.error(error.value);
        } finally {
            console.log(`[fileManagerStore loadFolderItems] FINALLY - Setting isDBLoading to false.`);
            isDBLoading.value = false;
        }
        console.log(`[fileManagerStore loadFolderItems] END - Target: ${targetFolderId}`);
    };

    const saveNewFileFromUpload = async (file: File) => {
        console.log(`[fileManagerStore saveNewFileFromUpload] START - Uploading ${file.name}`);
        const parentFolderId = currentFolderId.value; 
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore saveNewFileFromUpload] Aborted: DB is busy.`);
            ElMessage.warning('正在进行其他数据库操作，请稍后再试。');
            return;
        }
        isDBLoading.value = true;
        error.value = null;
        let finalName = file.name;
        try {
            console.log(`[fileManagerStore saveNewFileFromUpload] Checking name conflict for ${finalName}`);
            const baseName = file.name.replace(/\.(jdf|xml)$/i, '');
            const extension = file.name.split('.').pop()?.toLowerCase() || 'xml';
            let counter = 1;
            const existingNames = await idbService.getItemNamesByParent(parentFolderId);
            const nameSet = new Set(existingNames);
            while (nameSet.has(finalName)) {
                finalName = `${baseName} (${counter++}).${extension}`;
            }
            if (finalName !== file.name) {
                console.warn(`[fileManagerStore saveNewFileFromUpload] Name conflict. Renaming ${file.name} to ${finalName}`);
                ElMessage.warning(`文件名 ${file.name} 已存在，已自动重命名为 ${finalName}`);
            }
            const content = await file.text();
            console.log(`[fileManagerStore saveNewFileFromUpload] Adding file ${finalName} to DB.`);
            await idbService.addFile(finalName, content, parentFolderId);
            console.log(`[fileManagerStore saveNewFileFromUpload] File added. Reloading folder items...`);
            
            // Reset loading state BEFORE reloading
            isDBLoading.value = false;
            await loadFolderItems(parentFolderId); // Call action directly

            ElMessage.success(`文件 ${finalName} 已成功上传并保存。`);
        } catch (err: any) {
            error.value = `保存上传的文件 ${finalName} 失败: ${err.message}`;
            console.error('[fileManagerStore saveNewFileFromUpload] Error:', err);
            ElMessage.error(error.value);
            isDBLoading.value = false; // Ensure loading is false on error
            throw err;
        }
        console.log(`[fileManagerStore saveNewFileFromUpload] END - Uploaded ${finalName}`);
    };

    const createFileAndLoad = async (name: string): Promise<idbService.StoredJDFFileMeta | null> => {
        console.log(`[fileManagerStore createFileAndLoad] START - Creating file: ${name}`);
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore createFileAndLoad] Aborted: DB is busy.`);
            ElMessage.warning('正在进行其他数据库操作，请稍后再试。');
            return null;
        }
        isDBLoading.value = true;
        error.value = null;
        const template = `<?xml version="1.0" encoding="UTF-8"?>\n<Root>\n    <!-- New File -->\n</Root>`;
        let finalName = name;
        // Validation...
        if (!finalName || finalName.trim().length === 0) {
            error.value = "文件名不能为空。";
            console.error('[fileManagerStore createFileAndLoad] Error: Empty name.');
            ElMessage.error(error.value);
            isDBLoading.value = false;
            throw new Error(error.value);
        }
        if (finalName.includes('/') || finalName.includes('\\')) {
            error.value = "无效的文件名。名称不能包含斜杠。";
            console.error('[fileManagerStore createFileAndLoad] Error: Invalid name (contains slash).');
            ElMessage.error(error.value);
            isDBLoading.value = false;
            throw new Error(error.value);
        }
        // Ensure extension...
        if (!finalName.includes('.')) {
             finalName += '.xml';
             console.log(`[fileManagerStore createFileAndLoad] Appended .xml extension: ${finalName}`);
         } else {
             const allowedExtensions = ['.xml', '.jdf'];
             const extension = finalName.slice(finalName.lastIndexOf('.')).toLowerCase();
             if (!allowedExtensions.includes(extension)) {
                 error.value = `无效的文件扩展名: ${extension}。只允许 .xml 或 .jdf。`;
                 console.error(`[fileManagerStore createFileAndLoad] Error: Invalid extension ${extension}.`);
                 ElMessage.error(error.value);
                 isDBLoading.value = false;
                 throw new Error(error.value);
             }
         }
         try {
            // --- Check for unique name (auto-rename logic) ---
            console.log(`[fileManagerStore createFileAndLoad] Checking name conflict for ${finalName}`);
            let baseName = finalName.substring(0, finalName.lastIndexOf('.'));
            const extension = finalName.substring(finalName.lastIndexOf('.'));
            let counter = 1;
            const parentFolderId = currentFolderId.value;
            const existingItems = await idbService.getItemsByParent(parentFolderId); 
            let resolvedName = finalName; 
            while (existingItems.some(item => item.type === 'file' && item.name === resolvedName)) {
                resolvedName = `${baseName} (${counter++})${extension}`;
            }
            if (resolvedName !== finalName) {
                console.warn(`[fileManagerStore createFileAndLoad] Name conflict. Using ${resolvedName} instead of ${finalName}`);
                ElMessage.info(`文件名 ${finalName} 已存在，已自动使用 ${resolvedName}`);
            }
            finalName = resolvedName;
            // -----------------------------------------------
            console.log(`[fileManagerStore createFileAndLoad] Adding file ${finalName} to DB.`);
            const newFileMeta = await idbService.addFile(finalName, template, parentFolderId);
            console.log(`[fileManagerStore createFileAndLoad] File added (UUID: ${newFileMeta.uuid}). Reloading folder items...`);
            
            // Reset loading state BEFORE reloading
            isDBLoading.value = false;
            await loadFolderItems(parentFolderId);

            ElMessage.success(`新文件 ${finalName} 已创建。`);
            console.log(`[fileManagerStore createFileAndLoad] File ${finalName} created. Needs loading into editor.`);
            return newFileMeta;
        } catch (err: any) {
            if (!error.value) {
               error.value = `创建新文件 ${finalName} 失败: ${err.message}`;
               ElMessage.error(error.value);
            }
            console.error('[fileManagerStore createFileAndLoad] Error:', err);
            isDBLoading.value = false; // Ensure loading is false on error
            // Return null or rethrow depending on how the caller handles errors
            // Rethrowing ensures the dialog doesn't close unexpectedly in FileManagerView
            throw err; 
        } 
        console.log(`[fileManagerStore createFileAndLoad] END - Returning meta for ${finalName}`);
    };

    const deleteStoredFile = async (uuid: string) => {
        console.log(`[fileManagerStore deleteStoredFile] START - Deleting file ${uuid}`);
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore deleteStoredFile] Aborted: DB is busy.`);
            ElMessage.warning('正在进行其他数据库操作，请稍后再试。');
            return;
        }
        isDBLoading.value = true;
        error.value = null;
        try {
            console.log(`[fileManagerStore deleteStoredFile] Calling idbService.deleteFile for ${uuid}`);
            await idbService.deleteFile(uuid);
            console.log(`[fileManagerStore deleteStoredFile] File deleted. Reloading folder items...`);
            
            // Reset loading state BEFORE reloading
            isDBLoading.value = false;
            await loadFolderItems(currentFolderId.value);

        } catch (err: any) {
            error.value = `删除文件 (UUID: ${uuid}) 失败: ${err.message}`;
            console.error('[fileManagerStore deleteStoredFile] Error:', err);
            ElMessage.error(error.value);
            isDBLoading.value = false; // Ensure loading is false on error
            throw err;
        } 
        console.log(`[fileManagerStore deleteStoredFile] END - Deleted file ${uuid}`);
    };

    const createTemporaryFolder = async (baseName: string = '新建文件夹'): Promise<FilesystemItemMeta | null> => {
        console.log(`[fileManagerStore createTemporaryFolder] START - Creating folder with base name: ${baseName}`);
        const parentFolderId = currentFolderId.value;
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore createTemporaryFolder] Aborted: DB is busy.`);
            ElMessage.warning('正在进行其他数据库操作，请稍后再试。');
            return null;
        }
        isDBLoading.value = true;
        error.value = null;
        let finalName = baseName;
        try {
            // --- Check for unique name (among folders only) ---
            console.log(`[fileManagerStore createTemporaryFolder] Checking name conflict for ${finalName}`);
            let counter = 1;
            const existingItems = await idbService.getItemsByParent(parentFolderId);
            let resolvedName = baseName;
            const folderExists = (nameToCheck: string) => 
                existingItems.some(item => item.type === 'folder' && item.name === nameToCheck);
            if (folderExists(resolvedName)) {
                 counter = 2;
                 resolvedName = `${baseName} (${counter})`;
            }
            while (folderExists(resolvedName)) {
                counter++;
                resolvedName = `${baseName} (${counter})`;
            }
            finalName = resolvedName;
            // --------------------------------------------------
            console.log(`[fileManagerStore createTemporaryFolder] Calling idbService.addFolder with name: '${finalName}', parentId: ${parentFolderId}`);
            const newFolderMeta = await idbService.addFolder(finalName, parentFolderId);
            console.log(`[fileManagerStore createTemporaryFolder] Folder created (UUID: ${newFolderMeta.uuid}). Reloading folder items...`);
            
            // Reset loading state BEFORE reloading
            isDBLoading.value = false;
            await loadFolderItems(parentFolderId);

            ElMessage.success(`临时文件夹 "${finalName}" 已创建。`);
            // Find the item from the *now updated* list
            const createdItem = _currentItems.value.find(item => item.uuid === newFolderMeta.uuid); 
            console.log(`[fileManagerStore createTemporaryFolder] Returning created item meta: ${createdItem?.uuid}`);
            return createdItem || { ...newFolderMeta, type: 'folder' };
        } catch (err: any) {
            error.value = `创建临时文件夹失败: ${err.message}`;
            console.error('[fileManagerStore createTemporaryFolder] Error:', err);
            ElMessage.error(error.value);
            isDBLoading.value = false; // Ensure loading is false on error
            return null;
        } 
        console.log(`[fileManagerStore createTemporaryFolder] END - Created folder ${finalName}`);
    };

    const navigateToFolder = async (folderId: string | null) => {
        console.log(`[fileManagerStore navigateToFolder] START - Navigating to folderId: ${folderId}`); 
        const previousFolderId = currentFolderId.value;
        const previousBreadcrumbs = [...breadcrumbs.value];
        console.log(`[fileManagerStore navigateToFolder] Previous folderId: ${previousFolderId}`);
        
        // Check if already loading *before* calling loadFolderItems
        if (isDBLoading.value) {
             console.warn(`[fileManagerStore navigateToFolder] Aborted: DB is busy.`);
             return; 
        }

        // Call loadFolderItems - it will manage its own loading state
        await loadFolderItems(folderId);
        console.log(`[fileManagerStore navigateToFolder] loadFolderItems completed. Error state: ${error.value}`);
        
        // --- Breadcrumb Logic --- RESTORE --- 
        console.log('[fileManagerStore navigateToFolder] Starting breadcrumb update...');
        // Check for loading errors *after* loadFolderItems finishes
        if (error.value && currentFolderId.value === previousFolderId) {
            console.warn("[fileManagerStore navigateToFolder] Loading failed, reverting breadcrumbs.");
            breadcrumbs.value = previousBreadcrumbs;
            console.log('[fileManagerStore navigateToFolder] END - Reverted breadcrumbs due to error.');
            return;
        }
        // If load succeeded, update breadcrumbs
        if (folderId === ROOT_FOLDER_ID) {
            console.log('[fileManagerStore navigateToFolder] Target is ROOT. Resetting breadcrumbs.');
            breadcrumbs.value = [{ name: '根目录', uuid: ROOT_FOLDER_ID }];
        } else {
            console.log('[fileManagerStore navigateToFolder] Target is not ROOT. Calculating new breadcrumbs.');
            const existingIndex = breadcrumbs.value.findIndex(b => b.uuid === folderId);
            console.log(`[fileManagerStore navigateToFolder] Existing index for ${folderId}: ${existingIndex}`);
            if (existingIndex > -1) {
                console.log(`[fileManagerStore navigateToFolder] Folder found in existing breadcrumbs. Slicing to index ${existingIndex}.`);
                breadcrumbs.value = breadcrumbs.value.slice(0, existingIndex + 1);
            } else {
                console.log(`[fileManagerStore navigateToFolder] Folder ${folderId} not in existing breadcrumbs. Fetching folder info...`);
                try {
                    const folder = await idbService.getFolder(folderId!); 
                    if (folder) {
                        console.log(`[fileManagerStore navigateToFolder] Folder info found for ${folderId}. Pushing to breadcrumbs.`);
                        breadcrumbs.value.push({ name: folder.name, uuid: folder.uuid });
                    } else {
                        // Error Case 1: Folder not found by ID
                        console.error(`[fileManagerStore navigateToFolder] Folder with ID ${folderId} not found for breadcrumb. Breadcrumb might be incomplete.`);
                        ElMessage.error(`无法更新面包屑：找不到文件夹信息 (ID: ${folderId})。`);
                        // --- DO NOT RESET currentFolderId or reload root here --- 
                        // Keep the user in the folder they successfully loaded into via loadFolderItems.
                        // Breadcrumbs might be temporarily inaccurate, but the view shows the correct folder content.
                    }
                } catch (error: any) {
                    // Error Case 2: Other error fetching folder info
                    console.error('[fileManagerStore navigateToFolder] Error fetching folder name for breadcrumb:', error);
                    ElMessage.error(`更新面包屑时出错: ${error.message}`);
                    // --- DO NOT RESET currentFolderId or reload root here --- 
                } 
            }
        }
        console.log(`[fileManagerStore navigateToFolder] Breadcrumbs updated:`, JSON.stringify(breadcrumbs.value));
       
       // console.warn('[fileManagerStore navigateToFolder] Breadcrumb update logic TEMPORARILY DISABLED.');
       // --- END OF BREADCRUMB LOGIC RESTORE ---
       console.log(`[fileManagerStore navigateToFolder] END - Target: ${folderId}`);
    };

    const renameItem = async (uuid: string, newName: string, isFolder: boolean) => {
        console.log(`[fileManagerStore renameItem] START - Renaming item ${uuid} to ${newName} (isFolder: ${isFolder})`);
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore renameItem] Aborted: DB is busy.`);
            ElMessage.warning('正在进行其他数据库操作，请稍后再试。');
            return;
        }
        // Basic validation
        if (!newName || newName.trim().length === 0) {
            error.value = "名称不能为空。";
            console.error('[fileManagerStore renameItem] Error: Empty name.');
            ElMessage.error(error.value);
            throw new Error(error.value); // Rethrow for dialog handling
        }
        if (newName.includes('/') || newName.includes('\\')) {
            error.value = "无效的名称。名称不能包含斜杠。";
            console.error('[fileManagerStore renameItem] Error: Invalid name (contains slash).');
            ElMessage.error(error.value);
            throw new Error(error.value); // Rethrow for dialog handling
        }
        const itemToRename = _currentItems.value.find(item => item.uuid === uuid);
        if (!itemToRename) {
            error.value = "未找到要重命名的项目。";
            console.error(`[fileManagerStore renameItem] Item ${uuid} not found in currentItems.`);
            ElMessage.error(error.value);
            throw new Error(error.value);
        }
        const parentId = itemToRename.parentId;
        console.log(`[fileManagerStore renameItem] Item found. ParentId: ${parentId}. Checking name conflict...`);
        isDBLoading.value = true;
        error.value = null;
        try {
            // Check for name conflict within the current directory
            const existingItems = await idbService.getItemsByParent(parentId);
            let conflict = false;
            if (isFolder) {
                // Check against existing FOLDERS only
                conflict = existingItems.some(item => item.type === 'folder' && item.name === newName && item.uuid !== uuid);
                if (conflict) {
                   console.error(`[fileManagerStore renameItem] Error: Folder name "${newName}" already exists.`);
                   throw new Error(`文件夹 "${newName}" 已存在。`);
                }
            } else {
                // Check against existing FILES only
                conflict = existingItems.some(item => item.type === 'file' && item.name === newName && item.uuid !== uuid);
                if (conflict) {
                     console.error(`[fileManagerStore renameItem] Error: File name "${newName}" already exists.`);
                     throw new Error(`文件 "${newName}" 已存在。`);
                }
            }
            console.log(`[fileManagerStore renameItem] No name conflict found. Calling idbService.renameItem...`);
            await idbService.renameItem(uuid, newName, isFolder);
            console.log(`[fileManagerStore renameItem] Rename successful in DB. Reloading folder items...`);
            
            // Reset loading state BEFORE reloading
            isDBLoading.value = false;
            await loadFolderItems(currentFolderId.value);

            ElMessage.success(`${isFolder ? '文件夹' : '文件'} "${itemToRename.name}" 已重命名为 "${newName}"。`);
            
            // Update breadcrumbs if a renamed folder is part of the current path
            if (isFolder) {
                console.log(`[fileManagerStore renameItem] Item was a folder. Updating breadcrumbs if necessary...`);
                const crumbIndex = breadcrumbs.value.findIndex(b => b.uuid === uuid);
                if (crumbIndex > -1) {
                    console.log(`[fileManagerStore renameItem] Found renamed folder in breadcrumbs at index ${crumbIndex}. Updating name.`);
                    breadcrumbs.value[crumbIndex].name = newName;
                    breadcrumbs.value = [...breadcrumbs.value]; // Trigger reactivity
                }
            }
        } catch (err: any) {
            error.value = `重命名失败: ${err.message}`;
            console.error('[fileManagerStore renameItem] Error:', err);
            ElMessage.error(error.value);
            isDBLoading.value = false; // Ensure loading is false on error
            throw err; // Rethrow for dialog handling
        } 
        console.log(`[fileManagerStore renameItem] END - Renamed ${uuid} to ${newName}`);
    };

    const deleteStoredFolder = async (uuid: string, name: string) => {
        console.log(`[fileManagerStore deleteStoredFolder] START - Deleting folder ${uuid} (${name})`);
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore deleteStoredFolder] Aborted: DB is busy.`);
            ElMessage.warning('正在进行其他数据库操作，请稍后再试。');
            return;
        }
        const settingsStore = useSettingsStore();
        let confirmed = !settingsStore.confirmRecursiveDelete;
        let isFolderEmpty = false;
        
        isDBLoading.value = true; // Set loading before potential confirmation
        error.value = null;

        if (settingsStore.confirmRecursiveDelete) {
            console.log('[fileManagerStore deleteStoredFolder] Recursive delete confirmation enabled. Checking if folder is empty...');
            try {
                const itemsInside = await idbService.getItemsByParent(uuid);
                isFolderEmpty = itemsInside.length === 0;
                console.log(`[fileManagerStore deleteStoredFolder] Folder ${uuid} is ${isFolderEmpty ? 'empty' : 'not empty'}.`);
                if (!isFolderEmpty) {
                    console.log('[fileManagerStore deleteStoredFolder] Folder not empty. Showing confirmation dialog...');
                    // Release lock before showing modal
                    isDBLoading.value = false; 
                    confirmed = await confirm(
                        `确定要删除文件夹 "${name}" 及其所有内容吗？此操作无法撤销。`,
                    );
                    if (confirmed) {
                        // Re-acquire lock if confirmed
                         isDBLoading.value = true; 
                    } else {
                         return; // Exit if cancelled
                    }
                } else {
                    confirmed = true; // No need to confirm empty folder deletion
                }
            } catch (error: any) {
                console.error(`[fileManagerStore deleteStoredFolder] Error checking folder contents for ${uuid}:`, error);
                ElMessage.error(`检查文件夹内容时出错: ${error.message}`);
                isDBLoading.value = false; // Reset lock on check error
                return; // Stop deletion if check fails
            }
        } else {
            console.log('[fileManagerStore deleteStoredFolder] Recursive delete confirmation disabled. Proceeding directly...');
            confirmed = true; // Assume confirmed if setting is off
        }

        if (!confirmed) {
            console.log('[fileManagerStore deleteStoredFolder] Deletion cancelled by user...');
            isDBLoading.value = false; // Ensure lock is released if cancelled after check
             return; // Exit if user cancelled
        }

        // If we reach here, we are confirmed and isDBLoading should be true
        console.log('[fileManagerStore deleteStoredFolder] Proceeding with deletion...');
        // isDBLoading.value = true; // Should already be true if confirmed
        // error.value = null; // Already null
        try {
            console.log(`[fileManagerStore deleteStoredFolder] Calling idbService.deleteFolder (recursive) for folder ${uuid}`);
            await idbService.deleteFolder(uuid);
            console.log(`[fileManagerStore deleteStoredFolder] Recursive delete finished for ${uuid}. Refreshing current list...`);
            
            // Reset loading state BEFORE reloading
            isDBLoading.value = false;
            await loadFolderItems(currentFolderId.value);

            console.log(`[fileManagerStore deleteStoredFolder] Checking if deleted folder ${uuid} is in breadcrumbs...`);
            // Update breadcrumbs *after* list is refreshed
            const crumbIndex = breadcrumbs.value.findIndex(b => b.uuid === uuid);
            if (crumbIndex > -1) {
                console.log(`[fileManagerStore deleteStoredFolder] Removing deleted folder ${name} from breadcrumbs and navigating up.`);
                const parentCrumb = breadcrumbs.value[crumbIndex - 1];
                 // Reset loading state BEFORE navigating
                isDBLoading.value = false;
                await navigateToFolder(parentCrumb ? parentCrumb.uuid : ROOT_FOLDER_ID);
            }

            ElMessage.success(`文件夹 "${name}" ${isFolderEmpty ? '' : '及其内容 '}已删除。`);
        } catch (err: any) {
            error.value = `删除文件夹 "${name}" 失败: ${err.message}`;
            console.error('[fileManagerStore deleteStoredFolder] Error:', err);
            ElMessage.error(error.value);
            isDBLoading.value = false; // Ensure loading is false on error
            throw err;
        } 
        console.log(`[fileManagerStore deleteStoredFolder] END - Deleted folder ${uuid}`);
    };

    const moveItem = async (uuid: string, targetParentId: string | null, isFolder: boolean) => {
        console.log(`[fileManagerStore moveItem] START - Moving item ${uuid} to parent ${targetParentId} (isFolder: ${isFolder})`);
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore moveItem] Aborted: DB is busy.`);
            ElMessage.warning('正在进行其他数据库操作，请稍后再试。');
            return;
        }
        
        isDBLoading.value = true; // Set loading early
        error.value = null;

        try {
            // Fetch fresh item info using specific function based on type
            let itemToMove: StoredJDFFile | StoredJDFFolder | null = null;
            const fetchedItem = isFolder ? await idbService.getFolder(uuid) : await idbService.getFile(uuid);
            // Fix: Check if fetchedItem is defined before assigning
            if (fetchedItem) {
                 itemToMove = fetchedItem;
            }
            
             if (!itemToMove) {
                 throw new Error("未找到要移动的项目。");
             }

            // Prevent moving to the same folder
            if (itemToMove.parentId === targetParentId) {
                ElMessage.info("项目已在目标文件夹中。无需移动.");
                isDBLoading.value = false;
                return;
            }
            // Prevent moving a folder into itself
            if (isFolder && itemToMove.uuid === targetParentId) {
                throw new Error("无法将文件夹移动到其自身内部.");
            }
            // Note: Checking for moving into descendants is complex and skipped here.
            console.log(`[fileManagerStore moveItem] Pre-move checks passed for ${uuid}.`);
            
            console.log(`[fileManagerStore moveItem] Checking for conflict with name '${itemToMove.name}' in target parent ${targetParentId}`);
            const conflictingItemMeta = await idbService.getItemMetaByNameAndParent(itemToMove.name, targetParentId);
            
            let proceedWithMove = true;
            if (conflictingItemMeta) {
                console.warn(`[fileManagerStore moveItem] Conflict detected for name: ${itemToMove.name}. Conflicting item type: ${conflictingItemMeta.type}`);
                if (conflictingItemMeta.type === 'folder' && !isFolder || conflictingItemMeta.type === 'file' && isFolder) {
                    throw new Error(`移动失败：无法用${isFolder ? '文件夹' : '文件'} "${itemToMove.name}" 替换目标文件夹中的同名${conflictingItemMeta.type === 'folder' ? '文件夹' : '文件'}。`);
                }
                
                console.log(`[fileManagerStore moveItem] Showing conflict resolution dialog for ${itemToMove.name}.`);
                 // Release lock before showing modal
                isDBLoading.value = false;
                let resolvedAction: 'replace' | 'cancel' = 'cancel'; 
                try {
                    const { value } = await ElMessageBox.confirm(
                        `目标文件夹已包含同名${conflictingItemMeta.type === 'folder' ? '文件夹' : '文件'} "${itemToMove.name}"。是否替换？`, 
                        '移动冲突',
                        {
                            confirmButtonText: '替换',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    );
                    resolvedAction = 'replace';
                } catch (action) {
                    resolvedAction = 'cancel';
                    ElMessage.info('移动操作已取消。');
                    proceedWithMove = false; // Don't proceed
                }

                if (resolvedAction === 'replace') {
                    console.log(`[fileManagerStore moveItem] User chose REPLACE. Deleting conflicting item: ${conflictingItemMeta.uuid}`);
                    // Re-acquire lock before deleting
                    isDBLoading.value = true;
                    if (conflictingItemMeta.type === 'folder') {
                        await idbService.deleteFolder(conflictingItemMeta.uuid);
                    } else {
                        await idbService.deleteFile(conflictingItemMeta.uuid);
                    }
                    console.log('[fileManagerStore moveItem] Conflicting item deleted. Proceeding with move...');
                } else {
                     proceedWithMove = false; // Don't proceed if cancelled
                }
            } else {
                console.log(`[fileManagerStore moveItem] No name conflict found.`);
            }

            if (proceedWithMove) {
                 // Ensure lock is held if we are proceeding
                 if (!isDBLoading.value) isDBLoading.value = true; 
                 console.log(`[fileManagerStore moveItem] Calling idbService.moveItem for ${uuid} to parent ${targetParentId}`);
                 await idbService.moveItem(uuid, targetParentId, isFolder);
                 console.log('[fileManagerStore moveItem] Move successful in DB. Refreshing current view...');
                 
                 // Reset loading state BEFORE reloading
                 isDBLoading.value = false;
                 await loadFolderItems(currentFolderId.value);
                 
                 console.log('[fileManagerStore moveItem] Current view refreshed.');
                 ElMessage.success(`项目 "${itemToMove.name}" 移动成功。`);
             } // else: move was cancelled, do nothing further

        } catch (err: any) {
            error.value = `移动项目失败: ${err.message}`;
            console.error('[fileManagerStore moveItem] Error:', err);
            ElMessage.error(error.value);
            isDBLoading.value = false; // Ensure loading is false on error
            throw err;
        } 
        console.log(`[fileManagerStore moveItem] END - Moved ${uuid} to ${targetParentId}`);
    };

    const getAllFolders = async (): Promise<StoredJDFFolderMeta[]> => {
        console.log('[fileManagerStore getAllFolders] START - Fetching all folders.');
        try {
            const db = await idbService.getDB();
            const tx = db.transaction(idbService.FOLDERS_STORE_NAME, 'readonly');
            const store = tx.objectStore(idbService.FOLDERS_STORE_NAME);
            const folders: StoredJDFFolder[] = await store.getAll();
            await tx.done;
            const result = (folders ?? [])
                .filter(f => f && f.id !== undefined)
                .map(f => ({
                    id: f.id!,
                    uuid: f.uuid,
                    name: f.name,
                    parentId: f.parentId,
                    createdAt: f.createdAt,
                    lastModified: f.lastModified,
                } as StoredJDFFolderMeta))
                .sort((a, b) => a.name.localeCompare(b.name));
            console.log(`[fileManagerStore getAllFolders] END - Fetched ${result.length} folders.`);
            return result;
        } catch (error) {
            console.error("[fileManagerStore getAllFolders] Error fetching folders:", error);
            ElMessage.error("获取文件夹列表失败。");
            return [];
        }
    };

    const getFileDataForDownload = async (uuid: string): Promise<idbService.StoredJDFFile | null> => {
        console.log(`[fileManagerStore getFileDataForDownload] START - Getting data for file ${uuid}`);
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore getFileDataForDownload] Aborted: DB is busy.`);
            ElMessage.warning('正在进行其他数据库操作，请稍后再试。');
            return null;
        }
        isDBLoading.value = true;
        error.value = null;
        try {
            console.log(`[fileManagerStore getFileDataForDownload] Fetching content for UUID: ${uuid}`);
            const fileData = await idbService.getFile(uuid);
            if (!fileData) {
                error.value = `无法找到文件 (UUID: ${uuid}) 进行下载。`;
                console.error(`[fileManagerStore getFileDataForDownload] Error: File ${uuid} not found.`);
                ElMessage.error(error.value);
                isDBLoading.value = false; // Ensure loading is false on error
                return null;
            }
            console.log(`[fileManagerStore getFileDataForDownload] END - Successfully retrieved data for ${uuid}.`);
            isDBLoading.value = false; // Reset loading on success
            return fileData;
        } catch (err: any) {
            error.value = `获取文件内容失败 (UUID: ${uuid}): ${err.message}`;
            console.error('[fileManagerStore getFileDataForDownload] Error:', err);
            ElMessage.error(error.value);
            isDBLoading.value = false; // Ensure loading is false on error
            return null;
        } 
    };

    const getItemNamesByParent = async (parentId: string | null = ROOT_FOLDER_ID): Promise<string[]> => {
        // console.log(`[fileManagerStore getItemNamesByParent] Getting names for parent: ${parentId}`);
        try {
            return await idbService.getItemNamesByParent(parentId);
        } catch (error: any) {
            console.error(`[fileManagerStore getItemNamesByParent] Error for parent ${parentId}:`, error);
            error.value = `检查名称时出错: ${error.message}`;
            return [];
        }
    };

    // --- Inter-Store Communication Placeholders --- (Add logs here too)
    const loadFileIntoEditor = async (uuid: string) => {
        console.log(`[fileManagerStore loadFileIntoEditor] START - Loading file ${uuid} into editor.`);
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore loadFileIntoEditor] Aborted: DB is busy.`);
            ElMessage.warning('正在进行其他数据库操作，请稍后再试。');
            return;
        }
        isDBLoading.value = true;
        error.value = null;
        try {
            console.log(`[fileManagerStore loadFileIntoEditor] Getting content for ${uuid}`);
            const fileData = await idbService.getFile(uuid);
            if (!fileData) {
                throw new Error(`未找到 UUID 为 ${uuid} 的文件`);
            }
            console.log(`[fileManagerStore loadFileIntoEditor] Content found. Calling editorStore.loadContent...`);
            // Actual call to editor store
            const editorStore = useEditorStore(); // Get editor store instance
            await editorStore.loadContent(fileData.content, { 
                uuid: fileData.uuid, 
                name: fileData.name, 
                lastModified: fileData.lastModified 
            });
            ElMessage.success(`文件 "${fileData.name}" 加载成功。`);
            isDBLoading.value = false; // Reset loading on success
        } catch (err: any) {
            error.value = `加载文件 (UUID: ${uuid}) 失败: ${err.message}`;
            console.error('[fileManagerStore loadFileIntoEditor] Error:', err);
            ElMessage.error(error.value);
            isDBLoading.value = false; // Reset loading on error
        } 
        console.log(`[fileManagerStore loadFileIntoEditor] END - File ${uuid}`);
    };

    const saveEditorContent = async (uuid: string, content: string): Promise<boolean> => {
        console.log(`[fileManagerStore saveEditorContent] START - Saving content for file ${uuid}`);
        if (isDBLoading.value) {
            console.warn(`[fileManagerStore saveEditorContent] Aborted: DB is busy.`);
            ElMessage.warning('正在进行其他数据库操作，请稍后再试。');
            return false;
        }
        isDBLoading.value = true;
        error.value = null;
        try {
            console.log(`[fileManagerStore saveEditorContent] Calling idbService.updateFileContent for UUID: ${uuid}`);
            await idbService.updateFileContent(uuid, content);
            const now = new Date();

            // Update lastModified safely by finding index first
            console.log(`[fileManagerStore saveEditorContent] Updating lastModified in currentItems for ${uuid}`);
            const index = _currentItems.value.findIndex(item => item.type === 'file' && item.uuid === uuid);
            if (index > -1) {
                const itemToUpdate = _currentItems.value[index]; // Get the item via index
                _currentItems.value[index] = { ...(itemToUpdate!), lastModified: now }; 
                console.log(`[fileManagerStore saveEditorContent] Updated lastModified in currentItems for ${uuid}`);
            } else {
                console.log(`[fileManagerStore saveEditorContent] File ${uuid} not found in currentItems, skipping list update.`);
            }

            console.log(`[fileManagerStore saveEditorContent] DB update successful for ${uuid}. Notifying editor store...`);
            // Actual call to editor store
            const editorStore = useEditorStore(); // Get editor store instance
            editorStore.notifySaveSuccess(uuid, now); // Notify editor store
            isDBLoading.value = false; // Reset loading on success
            console.log(`[fileManagerStore saveEditorContent] END - Saved content for ${uuid}. Returning true.`);
            return true;
        } catch (err: any) {
            error.value = `保存文件 (UUID: ${uuid}) 失败: ${err.message}`;
            console.error('[fileManagerStore saveEditorContent] Error:', err);
            ElMessage.error(error.value);
             // Placeholder - Actual call needed
            // const editorStore = useEditorStore();
            // editorStore.notifySaveFailure(uuid);
            const editorStore = useEditorStore(); // Get editor store instance
            editorStore.notifySaveFailure(uuid); // Notify editor store
            isDBLoading.value = false; // Reset loading on error
            console.log(`[fileManagerStore saveEditorContent] END - Failed to save content for ${uuid}. Returning false.`);
            return false;
        } 
    };

    // --- New Sorting Action ---
    /**
     * Sets the sorting key and direction.
     * If the same key is provided, toggles the direction.
     * Otherwise, sets the new key and defaults to ascending direction.
     */
    const setSort = (newKey: SortKey) => {
        console.log(`[fileManagerStore setSort] Called with key: ${newKey}. Current: ${sortKey.value} ${sortDirection.value}`);
        if (sortKey.value === newKey) {
            // Toggle direction
            sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc';
             console.log(`[fileManagerStore setSort] Toggling direction for ${newKey} to ${sortDirection.value}`);
        } else {
            // Set new key, default to ascending
            sortKey.value = newKey;
            sortDirection.value = 'asc';
             console.log(`[fileManagerStore setSort] Setting new key ${newKey}, direction ${sortDirection.value}`);
        }
         // Computed property currentItems will automatically re-evaluate
    };
    // -------------------------

    // --- Return state, getters, and actions ---
    console.log('[fileManagerStore] Store initialization complete.');
    return {
        // State (internal _currentItems is not returned)
        currentFolderId,
        breadcrumbs,
        isDBLoading: readonly(isDBLoading), // Use readonly where appropriate
        error: readonly(error),
        // Getters/Computed
        currentFolderName,
        currentItems, // Return the computed, sorted list
        // Sorting State
        sortKey: readonly(sortKey),
        sortDirection: readonly(sortDirection),
        // Actions
        loadFolderItems,
        setSort,
        // ... (all other existing actions)
        saveNewFileFromUpload,
        createFileAndLoad,
        deleteStoredFile,
        createTemporaryFolder,
        navigateToFolder,
        renameItem,
        deleteStoredFolder,
        moveItem,
        getAllFolders,
        getFileDataForDownload,
        getItemNamesByParent,
        loadFileIntoEditor,
        saveEditorContent,
    };
}, {
    persist: {
        key: 'jdfsight-file-manager',
        // Restore pick to only persist currentFolderId
        pick: ['currentFolderId', 'sortKey', 'sortDirection'], 
        debug: import.meta.env.DEV,
    },
});